<template>
  <div class="post_wrapper">
    <div class="aside">
      <!-- 侧边栏组件 -->
      <PostAside @searchCity="searchCity" />
    </div>
    <div class="content">
      <div class="search_wrapper">
        <!-- 搜索框 -->
        <div class="search">
          <el-input
            v-model.trim="search"
            placeholder="请输入想去的地方，比如：广州"
            clearable
            @keyup.enter.native="handleSearch"
          >
            <template slot="append">
              <i class="el-icon-search" @click="handleSearch"></i>
            </template>
          </el-input>
        </div>
        <!-- 推荐城市 -->
        <div class="recommend">
          推荐：
          <span
            v-for="(city, index) in recommendCities"
            :key="index"
            @click="handleReC(city)"
          >
            {{ city }}
          </span>
        </div>
      </div>

      <div class="recommend_content">
        <div class="header">
          <h4>推荐攻略</h4>
          <div class="btn" @click="$router.push('/post/create')">
            <el-button type="primary" icon="el-icon-edit"> 写游记 </el-button>
          </div>
        </div>
        <!-- 推荐攻略组件 -->
        <div class="post_list" v-if="postList.length">
          <PostItem
            v-for="post in postList"
            :key="post.id"
            :postData="post"
            @click.native="$router.push(`/post/details?id=${post.id}`)"
          />
        </div>
        <div class="post_none" v-else>
          该城市还没有推荐呢，
          <span @click="$router.push(`/post/create?city=${$route.query.city}`)">
            我去写一篇~~
          </span>
        </div>
      </div>

      <!-- 分页插件 -->
      <div class="page_nation">
        <el-pagination
          background
          :hide-on-single-page="!total"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[3, 5, 10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageIndex"
          @size-change="sizeChange"
          @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: "",
      postList: [],
      total: 0,
      pageSize: 3,
      pageIndex: 1,
      recommendCities: ["广州", "上海", "北京"],
      timeId: null,
    };
  },
  watch: {
    // 监听路由参数变化,改变页码或搜索城市时重新发送请求
    "$route.query": {
      handler() {
        this.loadPost();
      },
    },
  },
  created() {
    // 解决刷新页码和一页显示多少条，分页组件会重置的问题
    this.pageSize = Number(this.$route.query.limit) || 3;
    this.pageIndex =
      Number(this.$route.query.star) / Number(this.$route.query.limit) + 1 || 1;

    // 添加短路运算保持刷新后页面数据的请求跟之前一样
    this.$router.push({
      path: "/post",
      query: {
        star: this.$route.query.star || (this.pageIndex - 1) * this.pageSize,
        limit: this.$route.query.limit || this.pageSize,
        city: this.$route.query.city,
      },
    });

    // 设置定时器查询是否更新了数据，没有则发送请求
    this.timeId = setTimeout(() => {
      if (!this.postList.length) {
        this.loadPost();
      }
    }, 500);
  },
  destroyed() {
    clearTimeout(this.timeId);
  },
  methods: {
    // 侧边栏点击菜单的推荐触发城市搜索
    searchCity(city) {
      this.$router.push({
        path: "/post",
        query: {
          star: 0,
          limit: this.$route.query.limit || this.pageSize,
          city,
        },
      });
    },
    // 点击推荐城市
    handleReC(city) {
      this.search = city;
      this.handleSearch();
    },

    // 按照城市搜索文章
    handleSearch() {
      if (!this.search) {
        this.$message.closeAll();
        this.$message.warning("请输入想去的地方");
        return;
      }
      this.$router.push({
        path: "/post",
        query: {
          star: 0,
          limit: this.$route.query.limit || this.pageSize,
          city: this.search,
        },
      });
    },

    // 一页显示多少条改变时触发
    sizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.$router.push({
        path: "/post",
        query: {
          ...this.$route.query,
          limit: newPageSize,
        },
      });
    },
    // 页码改变时触发
    currentChange(newPageIndex) {
      this.pageIndex = newPageIndex;
      this.$router.push({
        path: "/post",
        query: {
          ...this.$route.query,
          star: (newPageIndex - 1) * this.pageSize,
        },
      });
    },

    //   封装获取文章列表的请求
    loadPost() {
      this.$axios({
        url: "/posts",
        params: {
          _start:
            this.$route.query.star || (this.pageIndex - 1) * this.pageSize,
          _limit: this.$route.query.limit || this.pageSize,
          city: this.$route.query.city,
        },
      }).then((res) => {
        console.log(res);
        this.postList = res.data.data;
        this.total = res.data.total;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.post_wrapper {
  width: 1000px;
  margin: 20px auto;
  display: flex;
  justify-content: space-between;
  .aside {
    width: 260px;
  }
  .content {
    width: 700px;
    .search_wrapper {
      width: 100%;
      .search {
        border: 3px solid orange;
        /deep/ .el-input__inner {
          padding: 0 20px;
          outline: none;
          border: none;
        }
        /deep/ .el-input-group__append {
          background: none;
          border: none;
          color: orange;
          font-size: 24px;
        }
      }
      .recommend {
        padding: 10px 0;
        font-size: 12px;
        color: #666;
        span {
          margin-right: 6px;
          cursor: pointer;
        }
      }
    }
    .recommend_content {
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #eee;
        h4 {
          padding-bottom: 10px;
          font-size: 18px;
          font-weight: 400;
          color: orange;
          position: relative;
          &::after {
            position: absolute;
            bottom: -10px;
            left: 0;
            content: "";
            width: 100%;
            height: 2px;
            background: orange;
          }
        }
        .btn {
          padding-bottom: 10px;
        }
      }
      .post_none {
        padding: 60px 0;
        text-align: center;
        span {
          padding: 4px 0;
          color: orange;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
    .page_nation {
      margin: 20px 0;
      text-align: center;
    }
  }
}
</style>